/**
 *    Copyright 2009-2020 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.aapl.script;

import org.apache.ibatis.aapl.annotation.TableWatcher;
import org.apache.ibatis.aapl.script.creator.*;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SqlGenerator {

  private static Map<String, SqlCreator> generators = new HashMap<>();

  public static Pattern pattern = Pattern.compile("^[a-zA-Z]+\\(\\)");

  static {
    // 简单查询 自带 limit #{limit} offset #{offset} 可以在 TableWatcher 指定 order by
    // select() [except a,b,c] [where id = #{id}] [order by ()];
    generators.put("select()", new SelectSqlCreator());

    // 根据id查询一个 select xxx from table where id = #{id}
    // selectOne() [except a,b,c]
    generators.put("selectOne()", new SelectOneSqlCreator());

    // 查询总数量，类似select()
    // count() [where xxx]
    generators.put("count()", new CountSqlCreator());

    // 简单插入，根据传入参数，插值进入表中
    // insert() except a,b,c
    generators.put("insert()", new InsertSqlCreator());

    // 根据id进行删除 delete from table_x where id = #{id}
    // delete() [where xxx]
    generators.put("delete()", new DeleteSqlCreator());

    // 批量删除 传入id数组或列表，移除所有id在传入数组中的id。
    // 会生成这样的语句：
    // delete from table_x where id in
    // <foreach collection='list' separator=',' open='(' close=')' item='item'>
    //    #{item}
    // </foreach>
    generators.put("deleteBatch()", new DeleteBatchSqlCreator());

    // 更新一个对象的全部信息（更新null） 根据ID更新
    // updateAll() except a,b,c
    generators.put("updateAll()", new UpdateAllSqlCreator());

    // 更新一个对象的部分信息（不更新null） 根据ID更新
    // update() except a,b,c
    generators.put("update()", new UpdateSqlCreator());
  }

  public static String generateSql(String script, Method method, TableWatcher watcher) {

    if (watcher == null) {
      return script;
    }

    script = script.trim();

    Matcher matcher = pattern.matcher(script);
    if (matcher.find() == false) {
      return script;
    }

    String group = matcher.group(0);
    SqlCreator sqlCreator = generators.get(group);

    if (sqlCreator != null) {
      return sqlCreator.createSql(script, method, watcher);
    }

    return script;
  }
}
